﻿using System;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Mvc;

using mvcForum.Core;
using mvcForum.Core.Abstractions.Interfaces;
using mvcForum.Core.Specifications;
using mvcForum.Web.Interfaces;

using MVCThemes.Interfaces;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web {

	public class ForumThemeProvider : IThemeProvider {
		private const String themeKey = "mcvForumTheme";

		public void SetTheme(ActionExecutingContext filterContext) {
			// Get the board configuration.
			IConfiguration conf = DependencyResolver.Current.GetService<IConfiguration>();
			// Get the selected (if any) theme.
			String theme = conf.Theme;
			// Can the users select a custom theme?
			if (conf.AllowUserDefinedTheme) {
				// User can select custom theme, do we have a user?
				IWebUserProvider userProvider = DependencyResolver.Current.GetService<IWebUserProvider>();
				if (userProvider != null && userProvider.Authenticated) {
					// Yes, let's get him then!
					IRepository<ForumUser> repo = DependencyResolver.Current.GetService<IRepository<ForumUser>>();
					ForumUser user = userProvider.ActiveUser;
					// Did we get a user?
					if (user != null) {
						if (!String.IsNullOrWhiteSpace(user.Theme)) {
							theme = user.Theme;
						}
					}
				}
			}
			// Any theme found?
			if (!String.IsNullOrWhiteSpace(theme)) {
				if (Directory.Exists(Path.Combine(filterContext.HttpContext.Server.MapPath("~/themes"), theme))) {
					// Set the selected theme for later retrival by the ViewEngine.
					filterContext.HttpContext.Items.Add(ForumThemeProvider.themeKey, theme);
				}
			}
		}

		private String GetTheme(IDictionary items) {
			Object theme = items[ForumThemeProvider.themeKey];
			if (theme != null && !String.IsNullOrWhiteSpace((String)theme)) {
				return (String)theme;
			}

			return String.Empty;
		}

		public String GetTheme(ControllerContext controllerContext) {
			return this.GetTheme(controllerContext.HttpContext.Items);
		}

		public String GetTheme() {
			return this.GetTheme(HttpContext.Current.Items);
		}
	}
}